<?php

/**
 * This is the model class for table "blogpost".
 *
 * The followings are the available columns in table 'blogpost':
 * @property integer $id
 * @property integer $blogcategory_id
 * @property string $title
 * @property string $url
 * @property string $prev_content
 * @property string $full_content
 * @property string $tags
 * @property string $meta_title
 * @property string $meta_description
 * @property string $meta_keywords
 * @property integer $status
 * @property integer $create_time
 * @property integer $public_time
 * @property integer $author_id
 */
class Blogpost extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Blogpost the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{blogpost}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('title, url', 'required'),
			array('blogcategory_id, status, author_id', 'numerical', 'integerOnly'=>true),
			array('title, url, meta_title, meta_keywords', 'length', 'max'=>255),
        //    array('tags', 'match', 'pattern'=>'/^[\w\s,]+$/', 'message'=>'В тегах можно использовать только буквы.'),
            array('tags', 'normalizeTags'),
			array('prev_content, full_content, public_time, meta_description', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, blogcategory_id, title, url, status, create_time, public_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
            'category'=>array(self::BELONGS_TO, 'Blogcategory', 'blogcategory_id'),
            'comment'=>array(self::HAS_MANY, 'Blogcomment', 'post_id', 'condition'=>'status = 1'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'blogcategory_id' => 'Категория блога',
			'title' => 'Название поста',
            'url'=>'URL',
			'prev_content' => 'Предварительное содержание',
			'full_content' => 'Полное содержание',
			'tags' => 'Тэги',
            'meta_title'=>'Meta title',
            'meta_description'=>'Meta description',
            'meta_keywords'=>'Meta keywords',
			'status' => 'Статус',
			'create_time' => 'Дата и время создания',
			'public_time' => 'Дата публикации',
			'author_id' => 'Автор',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('blogcategory_id',$this->blogcategory_id);
		$criteria->compare('title',$this->title,true);
        $criteria->compare('url',$this->url,true);
//		$criteria->compare('prev_content',$this->prev_content,true);
//		$criteria->compare('full_content',$this->full_content,true);
//		$criteria->compare('tags',$this->tags,true);
//        $criteria->compare('meta_title',$this->meta_title,true);
//        $criteria->compare('meta_description',$this->meta_description,true);
//        $criteria->compare('meta_keywords',$this->meta_keywords,true);
		$criteria->compare('status',$this->status);
//		$criteria->compare('create_time',$this->create_time);
//		$criteria->compare('public_time',$this->public_time);
//		$criteria->compare('author_id',$this->author_id);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
    
    
    public function beforeSave()
    {
        if($this->isNewRecord)
            $this->create_time = time();
        
         $this->public_time = strtotime($this->public_time);
        return parent::beforeSave();
    }
    
    
    protected function afterSave()         //Для тегов
    {
    parent::afterSave();
    Blogtag::model()->updateFrequency($this->_oldTags, $this->tags);
    }
  
    
    private $_oldTags;
 
     protected function afterFind() 
     {
     $date = date('d-m-Y', $this->public_time);
     $this->public_time = $date;
     
      $this->_oldTags=$this->tags;            //Записывает старые теги в свойство _oldTags
     parent::afterFind();
    }
    
    
    protected function afterDelete()    //После удаления поста
    {
    parent::afterDelete();
//    Comment::model()->deleteAll('post_id='.$this->id);
    Blogtag::model()->updateFrequency($this->tags, '');
    }
    
    
    
    /**  Валидатор тегов.  чтобы тэги были одинаковыми, и разделялись запятыми  */
    public function normalizeTags($attribute,$params)
    {
     $this->tags=Blogtag::array2string(array_unique(Blogtag::string2array($this->tags)));
    }
    
    
    
 // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++   
 
	public function tagLinks($id)  /**  Метод возвращает список ссылок по тегам */
	{
	    $link = array();
		$links=array();
    
    $tags = self::model()->findAllByPk($id);   //Найти все записи текущего поста
    $link = explode(',', $tags[0]->tags);      //Разбить строку по запятым на отдельные слова
    foreach($link as $item)
    {
        $links[] = CHtml::link(CHtml::encode(trim($item)), array('blog/tagsearch', 'tag'=>trim($item)));    //Присвоить массиву ссылку
    }

    return $links;
    
	}
  
  
  
    
}